package com.company.cloud.mall.modules.app.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.company.cloud.common.bean.LoginSimpleUserInfo;
import com.company.cloud.common.mq.redis.client.consumer.MQSaasResult;
import com.company.cloud.mall.constant.ShopConstant.PayConfirmWay;
import com.company.cloud.mall.modules.app.controller.req.PayResultReportParam;
import com.company.cloud.mall.modules.app.service.ShopOrderPayService;
import com.company.cloud.pay.constant.ThirdPayConfirmWayEnum;
import com.company.cloud.pay.core.enums.SignType;
import com.company.cloud.pay.core.kit.HttpKit;
import com.company.cloud.pay.core.kit.WxPayKit;
import com.company.cloud.pay.modules.app.controller.WXPayNotifyController;
import com.company.cloud.pay.modules.bus.producer.PayProducer;
import com.company.cloud.pay.modules.cache.model.PayChannelConfigModel;
import com.company.cloud.pay.modules.cache.service.PayCacheService;
import com.company.cloud.pay.modules.pay.service.PaymentOrderService;
import com.company.cloud.pay.modules.third.models.ThirdPayNotifyResp;
import com.company.cloud.pay.modules.third.utils.WxPayStateConvertKit;

import io.swagger.annotations.Api;
import lombok.extern.log4j.Log4j2;

@Log4j2
@Controller
@RequestMapping("/pay")
@Api(tags = "PAY_微信支付通知服务")
public class WXPayNotify2Controller {
	
	@Autowired
	private PayCacheService payCacheService;

	@Autowired
	private PayProducer payProducerUtils;

	@Autowired
	private PaymentOrderService paymentOrderService;
	
	@Autowired
	private ShopOrderPayService shopOrderPayService;
	

	private PayChannelConfigModel getPayChannelConfig(HttpServletRequest request) {
		try {
			// String path=request.getRequestURI();
			String path = request.getServletPath();
			String[] strs = path.split("/");
			String payConfigId = strs[strs.length - 2];
			PayChannelConfigModel payConfig = payCacheService.getPayChannelConfigByCache(Integer.parseInt(payConfigId));
			return payConfig;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	private void processPayNotify(PayChannelConfigModel payConfig,Map<String, String> params) {
		ThirdPayNotifyResp resp=new ThirdPayNotifyResp();
		resp.setMchId(params.get("mch_id"));
		resp.setAppId(params.get("appid"));
		resp.setTotalFee(params.get("total_fee"));
		resp.setResultCode(params.get("result_code"));
		resp.setIsSubscribe(params.get("is_subscribe"));
		resp.setOpenid(params.get("openid"));
		resp.setTransactionId(params.get("transaction_id"));
		resp.setOutTradeNo(params.get("out_trade_no"));
		resp.setAttach(params.get("attach"));
		resp.setTradeType(params.get("trade_type"));
		resp.setTimeEnd(params.get("time_end"));
		resp.setState(WxPayStateConvertKit.convertPayStateStr(resp.getResultCode()));
		paymentOrderService.notifyCallBack(ThirdPayConfirmWayEnum.ThirdCallback_Confirm,payConfig.getServiceCode(),payConfig.getCompanyNo(),resp);
		
		System.out.println("+++++++++支付结果消费++++++++++");
		PayResultReportParam bizParams=new PayResultReportParam();
		bizParams.setSn(resp.getOutTradeNo());
		bizParams.setState(resp.getState());
		bizParams.setMemo("第三方支付回调");
		bizParams.setThirdState(resp.getResultCode());
		
		LoginSimpleUserInfo userInfo=new LoginSimpleUserInfo();
		userInfo.setId(-1);
		userInfo.setIp("127.0.0.1");
		
		shopOrderPayService.payReport(bizParams, PayConfirmWay.ThirdCallback_Confirm, userInfo);
	
	}
	
	private void processRefundNotify(PayChannelConfigModel payConfig,Map<String, String> params) {
		
	}
	
	private String notifyReturnOk() {
		Map<String, String> xml = new HashMap<String, String>(2);
		xml.put("return_code", "SUCCESS");
		xml.put("return_msg", "OK");
		return WxPayKit.toXml(xml);
	}
	
	private String notifyReturnFail(String msg) {
		Map<String, String> xml = new HashMap<String, String>(2);
		xml.put("return_code", "FAIL");
		xml.put("return_msg", msg);
		return WxPayKit.toXml(xml);
	}

	/**
	 * 支付异步通知
	 */
	@RequestMapping(value = "/wx/{payConfigId}/payNotify", method = { RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public String payNotify(HttpServletRequest request) {
		System.out.println("+++++WX 微信支付异步通知 ++++++++++++++++");
		PayChannelConfigModel payConfig = this.getPayChannelConfig(request);
		if (payConfig == null) {
			return this.notifyReturnFail("参数格式校验错误");
		}
		String xmlMsg = HttpKit.readData(request);
		log.debug("+++++支付通知 = " + xmlMsg);
		Map<String, String> params = WxPayKit.xmlToMap(xmlMsg);
		String returnCode = params.get("return_code");
		if (WxPayKit.verifyNotify(params, payConfig.getPayChannelParam().getApiKey(), SignType.MD5)) {
			if (WxPayKit.codeIsOk(returnCode)) {
				// 更新支付订单信息
				this.processPayNotify(payConfig,params);
				// 发送通知
				return this.notifyReturnOk();
			}
		}
		return this.notifyReturnFail("签名失败");
	}

	/**
	 * 退款通知
	 */
	@RequestMapping(value = "/wx/{payConfigId}/refundNotify", method = { RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public String refundNotify(HttpServletRequest request) {
		PayChannelConfigModel payConfig = this.getPayChannelConfig(request);
		if (payConfig == null) {
			return this.notifyReturnFail("参数格式校验错误");
		}
		String xmlMsg = HttpKit.readData(request);
		log.debug("+++++退款通知 = " + xmlMsg);
		Map<String, String> params = WxPayKit.xmlToMap(xmlMsg);
		String returnCode = params.get("return_code");
		if (WxPayKit.verifyNotify(params, payConfig.getPayChannelParam().getApiKey(), SignType.MD5)) {
			if (WxPayKit.codeIsOk(returnCode)) {
				// 更新退款订单信息
				this.processRefundNotify(payConfig,params);
				// 发送通知
				this.notifyReturnOk();
			}
		}
		return this.notifyReturnFail("签名失败");
	}
	

	

}
